package com.cnblsp2.android.study.dbandio.files;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.cnblsp2.android.study.dbandio.R;

public class FileActivity extends Activity {

	private EditText writerEtxt = null;
	private EditText showerETxt = null;
	private Button writerBtn = null;
	private Button showerBtn = null;

	private static final String FILE_NAME = "cnblsp2.bin";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_file);

		writerEtxt = (EditText) this.findViewById(R.id.activity_file_writer_etxt);
		showerETxt = (EditText) this.findViewById(R.id.activity_file_show_etxt);
		writerBtn = (Button) this.findViewById(R.id.activity_file_writer_btn);
		showerBtn = (Button) this.findViewById(R.id.activity_file_show_btn);
		writerBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String content = writerEtxt.getText().toString();
				if (content == null || "".equals(content)) {
					Toast.makeText(FileActivity.this, "请输入文本信息!", Toast.LENGTH_SHORT).show();;
					return;
				}
				write(content);

			}
		});

		showerBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String context = read();
				if (context == null || "".equals(context)) {
					Toast.makeText(FileActivity.this, "请先输入并保存数据到文件!", Toast.LENGTH_SHORT);
					return;
				}
				showerETxt.setText(context);
			}
		});

	}

	private String read() {
		try {
			FileInputStream fis = openFileInput(FILE_NAME);
			byte[] buff = new byte[1024];
			int hasRead = 0;
			StringBuilder sb = new StringBuilder("");
			while ((hasRead = fis.read(buff)) > 0) {
				sb.append(new String(buff, 0, hasRead));
			}
			return sb.toString();
		} catch (FileNotFoundException e) {
			Toast.makeText(FileActivity.this, "文件未找到:" + FILE_NAME, Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void write(String content) {
		try {
			// 以追加模式打开文件输出流
			FileOutputStream fos = openFileOutput(FILE_NAME, MODE_APPEND);

			PrintStream ps = new PrintStream(fos);

			ps.println(content);

			ps.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
